package br.com.mrezzosoftware.machineguardianmonitorprotect;

import br.com.mrezzosoftware.machineguardianmonitorprotect.core.Constantes;
import br.com.mrezzosoftware.machineguardianmonitorprotect.core.PreferencesUtil;
import br.com.mrezzosoftware.machineguardianmonitorprotect.core.ServidorWeb;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.UnsupportedLookAndFeelException;

/**
 *
 * @author MRezzoSoftware
 */
public class MGMPRegistrarMaquina extends javax.swing.JDialog {
    
    /**
     * Creates new form MGMPMain
     */
    public MGMPRegistrarMaquina() {
        definirAparencia();
        initComponents();
        configuracoes();
    }

    private void definirAparencia() {
        try {

            javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());

        } catch (ClassNotFoundException ex) {
            Logger.getLogger(MGMPRegistrarMaquina.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(MGMPRegistrarMaquina.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(MGMPRegistrarMaquina.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedLookAndFeelException ex) {
            Logger.getLogger(MGMPRegistrarMaquina.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblEmailCadastrado = new javax.swing.JLabel();
        txtEmailCadastrado = new javax.swing.JTextField();
        lblEmailCadastradoInfo = new javax.swing.JLabel();
        lblIdMaquina = new javax.swing.JLabel();
        lblIdMaquinaInfo = new javax.swing.JLabel();
        txtIdMaquina = new javax.swing.JTextField();
        btnRegistrarMaquina = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setBackground(new java.awt.Color(236, 233, 216));

        lblEmailCadastrado.setText("E-mail cadastrado:");

        lblEmailCadastradoInfo.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        lblEmailCadastradoInfo.setForeground(new java.awt.Color(255, 0, 0));
        lblEmailCadastradoInfo.setText(" ? ");
        lblEmailCadastradoInfo.setToolTipText("E-mail utilizado no cadastro da sua conta via celular.");

        lblIdMaquina.setText("ID da Máquina:");

        lblIdMaquinaInfo.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        lblIdMaquinaInfo.setForeground(new java.awt.Color(255, 0, 0));
        lblIdMaquinaInfo.setText(" ? ");
        lblIdMaquinaInfo.setToolTipText("Descrição da máquina para acesso via celular.");

        btnRegistrarMaquina.setText("Registrar");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtIdMaquina)
                    .addComponent(txtEmailCadastrado)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(lblEmailCadastrado)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(lblEmailCadastradoInfo))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(lblIdMaquina)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(lblIdMaquinaInfo)))
                        .addGap(0, 83, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(btnRegistrarMaquina)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblEmailCadastrado)
                    .addComponent(lblEmailCadastradoInfo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtEmailCadastrado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblIdMaquina)
                    .addComponent(lblIdMaquinaInfo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtIdMaquina, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnRegistrarMaquina)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void configuracoes() {

        this.setLocationRelativeTo(null);
        this.setResizable(false);
        this.setVisible(true);
        //PreferencesUtil.getInstance().registrarValor(Constantes.PREF_TEMPO_ATUALIZACAO, "120000");
        PreferencesUtil.getInstance().registrarValor(Constantes.PREF_TEMPO_ATUALIZACAO, "10000");

        this.addWindowListener(new java.awt.event.WindowAdapter() {

            @Override
            public void windowClosing(java.awt.event.WindowEvent e) {
                System.exit(0);
                MachineGuardianMonitorProtect.executar = true;
            }
        });

        btnRegistrarMaquina.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                registrarIdMaquinaMonitorada(txtEmailCadastrado.getText(), txtIdMaquina.getText());
            }
        });
    }


    private void registrarIdMaquinaMonitorada(String email, String idMaquina) {

        String retornoServidor = ServidorWeb.cadastrarMaquina(email, idMaquina);
        
        System.out.println("retornoServidor: \"" + retornoServidor + "\""); 
        
        if (retornoServidor.equalsIgnoreCase("MAQ-JA-CAD")) {
            
            javax.swing.JOptionPane.showMessageDialog(this,
                    "Máquina já cadastrada.\n"
                    + "Já existe uma máquina com este mesmo nome no servidor para o email " + email,
                    "Retorno do servidor",
                    javax.swing.JOptionPane.ERROR_MESSAGE);
        } else if (retornoServidor.equalsIgnoreCase("MAIL-NAO-CAD")) {
            javax.swing.JOptionPane.showMessageDialog(this,
                    "E-mail não cadastrado.\n"
                    + "O e-mail " + email + " não está cadastrado.\n"
                    + "Para utilizar o programa você deve cadastrar uma conta com e-mail no aplicativo do celular.",
                    "Retorno do servidor",
                    javax.swing.JOptionPane.ERROR_MESSAGE);
        } else if (retornoServidor.equalsIgnoreCase("CAD-MAQ-SUC")) {
            PreferencesUtil.getInstance().registrarValor(Constantes.PREF_EMAIL, email);
            PreferencesUtil.getInstance().registrarValor(Constantes.PREF_ID_MAQUINA, idMaquina);
            
            javax.swing.JOptionPane.showMessageDialog(this,
                    "Máquina registrada.\n"
                    + "Utilize o programa no celular para realizar as ações desejadas.",
                    "Retorno do servidor",
                    javax.swing.JOptionPane.INFORMATION_MESSAGE);
            
            MachineGuardianMonitorProtect.executar = true;
            this.dispose();
        }
        


    }

    private void habilitarCampo(javax.swing.JComponent componente) {
        componente.setEnabled(true);
    }

    private void desabilitarCampo(javax.swing.JComponent componente) {
        componente.setEnabled(false);
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnRegistrarMaquina;
    private javax.swing.JLabel lblEmailCadastrado;
    private javax.swing.JLabel lblEmailCadastradoInfo;
    private javax.swing.JLabel lblIdMaquina;
    private javax.swing.JLabel lblIdMaquinaInfo;
    private javax.swing.JTextField txtEmailCadastrado;
    private javax.swing.JTextField txtIdMaquina;
    // End of variables declaration//GEN-END:variables
}
